package com.conv.shop.business.service;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.util.ObjectUtil;
import com.conv.shop.business.domain.Consumer;
import com.conv.shop.business.domain.ConsumerExample;
import com.conv.shop.business.domain.StoreUser;
import com.conv.shop.business.domain.StoreUserExample;
import com.conv.shop.business.mapper.StoreMapper;
import com.conv.shop.business.mapper.StoreUserMapper;
import com.conv.shop.business.req.StoreUserPasswordReq;
import com.conv.shop.business.resp.StoreLoginResp;
import com.conv.shop.common.enums.BusinessExceptionEnum;
import com.conv.shop.common.exception.BusinessException;
import com.conv.shop.business.mapper.ConsumerMapper;
import com.conv.shop.business.req.ToConsumerReq;
import com.conv.shop.business.resp.ConsumerLoginResp;
import com.conv.shop.business.resp.ConsumerResp;
import com.conv.shop.business.util.JwtUtil;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Service
public class ConsumerService {
    @Resource
    ConsumerMapper consumerMapper;
    @Resource
    StoreUserMapper storeUserMapper;
    @Resource
    StoreMapper storeMapper;

    /**
     * 消费者列表
     * @return List<ConsumerResp>
     */
    public List<ConsumerResp> getList(){
        ConsumerExample consumerExample = new ConsumerExample();
        consumerExample.createCriteria().andConsumerIdIsNotNull();
        List<Consumer> consumerList = consumerMapper.selectByExample(consumerExample);
        return BeanUtil.copyToList(consumerList, ConsumerResp.class);

    }


    /**
     * 消费者登录并且生成token
     * @param （ToConsumerReq req）
     * @return ConsumerLoginResp
     */
    public ConsumerLoginResp login(ToConsumerReq req){
        String phone = req.getPhone();
        String password = req.getPassword();
        Consumer consumerDB= selectByMobile(phone);
        //如果手机号存在，则提示手机号已存在
        if(ObjectUtil.isNull(consumerDB)){
            throw new BusinessException(BusinessExceptionEnum.MEMBER_MOBILE_EXIST);
        }
        //校验密码
        if(!consumerDB.getPassword().equals(password)){
            throw new BusinessException(BusinessExceptionEnum.PASSWORD_ERROR);
        }
        ConsumerLoginResp consumerLoginResp= BeanUtil.copyProperties(consumerDB, ConsumerLoginResp.class);
        String token = JwtUtil.createToken(consumerLoginResp.getConsumerId(),consumerLoginResp.getPhone());
        consumerLoginResp.setToken(token);
        return consumerLoginResp;

    }

    /**
     * 根据手机号码检索用户
     * @param phone
     * @return Consumer
     */
    public Consumer selectByMobile(String phone) {
        ConsumerExample consumerExample = new ConsumerExample();
        consumerExample.createCriteria().andPhoneEqualTo(phone);
        List<Consumer> list= consumerMapper.selectByExample(consumerExample);
        if(CollUtil.isEmpty(list)){
            return null;
        }else {
            return list.get(0);
        }
    }

    /**
     * 根据用户名检索用户
     * @param consumerName
     * @return Consumer
     */
    public Consumer selectByName(String consumerName) {
        ConsumerExample consumerExample = new ConsumerExample();
        consumerExample.createCriteria().andPhoneEqualTo(consumerName);
        List<Consumer> list= consumerMapper.selectByExample(consumerExample);
        if(CollUtil.isEmpty(list)){
            return null;
        }else {
            return list.get(0);
        }
    }

    /**
     * 根据邮箱号检索用户
     * @param email
     * @return Consumer
     */
    public Consumer selectByEmail(String email) {
        ConsumerExample consumerExample = new ConsumerExample();
        consumerExample.createCriteria().andPhoneEqualTo(email);
        List<Consumer> list= consumerMapper.selectByExample(consumerExample);
        if(CollUtil.isEmpty(list)){
            return null;
        }else {
            return list.get(0);
        }
    }

    /**
     *  消费者注册
     * @param （ToConsumerReq req）
     * @return boolean
     */
    public boolean save(ToConsumerReq req){
        if(ObjectUtil.isNotNull(selectByMobile(req.getPhone()))){
            throw new BusinessException(BusinessExceptionEnum.MEMBER_MOBILE_EXIST);
        }
        Consumer consumer = new Consumer();
        Date now = DateTime.now();
        consumer.setPhone(req.getPhone());
        consumer.setConsumerName(req.getConsumerName());
        consumer.setPassword(req.getPassword());
        consumer.setRegisterTime(now);
        int i = consumerMapper.insert(consumer);
        if (i!=0){
            return true;
        }else {
            return false;
        }
    }

    /**
     * 获取消费者信息详情
     * @param consumerId
     * @return Consumer
     */
    public Consumer getUserDetails(Integer consumerId) {
       return consumerMapper.selectByPrimaryKey(consumerId);
    }

    /**
     * 更新消费者信息
     * @param （ToConsumerReq req）
     * @return boolean
     */
    public boolean update(ToConsumerReq req){
        ConsumerExample consumerExample = new ConsumerExample();
        consumerExample.createCriteria().andConsumerIdEqualTo(req.getConsumerId());
        Consumer consumer = new Consumer();
        consumer.setConsumerId(req.getConsumerId());
        consumer.setConsumerName(req.getConsumerName());
        consumer.setPhone(req.getPhone());
        consumer.setEmail(req.getEmail());
        int i = consumerMapper.updateByExampleSelective(consumer, consumerExample);
        if (i!=0){
            return true;
        }else {
            return false;
        }
    }

    /**
     * 商家登录
     * @param req
     * @return StoreLoginResp
     */
    public StoreLoginResp adminLogin(ToConsumerReq req){
        String phone = req.getPhone();
        String password = req.getPassword();
        Consumer consumerDB= selectByMobile(phone);
        //如果手机号不存在，则插入一条记录
        if(ObjectUtil.isNull(consumerDB)){
            return null;
        }
        StoreUserExample storeUserExample = new StoreUserExample();
        storeUserExample.createCriteria().andConsumerIdEqualTo(consumerDB.getConsumerId());
        List<StoreUser> storeUsers =  storeUserMapper.selectByExample(storeUserExample);
        if(storeUsers.isEmpty()){
            return null;
        }
        StoreUser storeUser = storeUsers.get(0);
        //校验密码
        if(!consumerDB.getPassword().equals(password)){
            return null;
        }
        StoreLoginResp storeLoginResp= BeanUtil.copyProperties(consumerDB, StoreLoginResp.class);
        String token = JwtUtil.createToken(storeLoginResp.getConsumerId(),storeLoginResp.getPhone());
        storeLoginResp.setToken(token);
        storeLoginResp.setRole(storeUser.getRole());
        storeLoginResp.setStore(storeMapper.selectByPrimaryKey(storeUser.getStoreId()));
        return storeLoginResp;
    }

    /**
     * 商品用户修改密码
     * @param req
     * @return boolean
     */
    public boolean StoreUserPasswd(StoreUserPasswordReq req){
        Consumer storeUser = consumerMapper.selectByPrimaryKey(req.getConsumerId());
        if(storeUser.getPassword().equals(req.getOldPassword())){
            storeUser.setPassword(req.getNewPassword());
            consumerMapper.updateByPrimaryKey(storeUser);
            return true;
        }else {
            return false;
        }
    }
}
